#import "SettingsViewController.h"

@interface SettingsViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *sectionTitles;
@property (nonatomic, strong) NSArray *itemTitles;
@property (nonatomic, strong) NSArray *itemIcons;
@property (nonatomic, strong) NSArray *itemAccessoryTypes;
@property (nonatomic, assign) BOOL isMainSwitchOn;
@property (nonatomic, strong) NSMutableArray *cellHeights;

@end

@implementation SettingsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isMainSwitchOn = YES;
    [self setupData];
    [self setupUI];
}

- (void)setupData {
    self.title = @"手机消息同步";
    
    self.sectionTitles = @[@"手机消息同步", @"允许下类消息显示至眼镜", @"通知防重复", @"通知时静音"];
    
    self.itemTitles = @[
        @[@"手机消息同步"],
        @[@"电话", @"短信", @"日程", @"闹钟", @"手机App"],
        @[@"通知防重复"],
        @[@"通知时静音"]
    ];
    
    self.itemIcons = @[
        @[],
        @[@"phone", @"message", @"calendar", @"clock", @"app"],
        @[],
        @[]
    ];
    
    self.itemAccessoryTypes = @[
        @[@"switch"],
        @[@"detail", @"detail", @"detail", @"detail", @"detail"],
        @[@"switch"],
        @[@"switch"]
    ];
    
    // 初始化cell高度数组
    self.cellHeights = [NSMutableArray array];
    for (NSArray *section in self.itemTitles) {
        NSMutableArray *heights = [NSMutableArray array];
        for (int i = 0; i < section.count; i++) {
            [heights addObject:@(50)];
        }
        [self.cellHeights addObject:heights];
    }
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor systemGroupedBackgroundColor];
    
    // 返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:[UIImage systemImageNamed:@"chevron.left"] forState:UIControlStateNormal];
    backButton.frame = CGRectMake(0, 0, 44, 44);
    [backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    // 信息按钮
    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [infoButton setImage:[UIImage systemImageNamed:@"info.circle"] forState:UIControlStateNormal];
    infoButton.frame = CGRectMake(0, 0, 44, 44);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
    
    // TableView
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleInsetGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor systemGroupedBackgroundColor];
    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedSectionHeaderHeight = 44;
    self.tableView.sectionFooterHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedSectionFooterHeight = 44;
    [self.view addSubview:self.tableView];
}

#pragma mark - Actions

- (void)backButtonTapped {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)mainSwitchValueChanged:(UISwitch *)sender {
    // 先改变状态
    self.isMainSwitchOn = sender.isOn;
    // 刷新整个tableView
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionTitles.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.isMainSwitchOn && section > 0) {
        return 0;
    }
    return [self.itemTitles[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
    }
    
    // 重置cell的所有属性
    cell.imageView.image = nil;
    cell.accessoryView = nil;
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.detailTextLabel.text = nil;
    
    // 配置cell
    cell.textLabel.text = self.itemTitles[indexPath.section][indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    
    // 设置图标
    if (indexPath.section == 1) {
        NSString *iconName = self.itemIcons[1][indexPath.row];
        if (iconName.length > 0) {
            cell.imageView.image = [UIImage systemImageNamed:iconName];
        }
    }
    
    // 设置附加视图
    NSString *accessoryType = self.itemAccessoryTypes[indexPath.section][indexPath.row];
    if ([accessoryType isEqualToString:@"switch"]) {
        UISwitch *switchView = [[UISwitch alloc] init];
        switchView.onTintColor = [UIColor systemGreenColor];
        
        // 设置开关状态
        if (indexPath.section == 0) {
            switchView.on = self.isMainSwitchOn;
            [switchView addTarget:self action:@selector(mainSwitchValueChanged:) forControlEvents:UIControlEventValueChanged];
        } else {
            // 其他开关的状态跟随主开关
            switchView.on = self.isMainSwitchOn;
            switchView.enabled = self.isMainSwitchOn;
        }
        
        cell.accessoryView = switchView;
    } else if ([accessoryType isEqualToString:@"detail"]) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if (indexPath.section == 1) {
            cell.detailTextLabel.text = indexPath.row == 0 ? @"允许" : @"不允许";
            cell.detailTextLabel.textColor = [UIColor systemGrayColor];
        }
    }
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0 || (section > 0 && self.isMainSwitchOn)) {
        return self.sectionTitles[section];
    }
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    if (!self.isMainSwitchOn && section > 0) {
        return nil;
    }
    
    if (section == 0) {
        return @"开启后，手机收到的消息，可在眼镜的显示屏中显示。\n提示：手机「勿扰/驾驶/...」模式下被过滤的消息无法显示到眼镜。";
    } else if (section == 2) {
        return @"开启后，手机解锁使用时收到消息，眼镜不再重复显示。";
    }
    return nil;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 2 || section == 3) {
        return 20;
    }
    return UITableViewAutomaticDimension;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 2 || section == 3) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)];
        headerView.backgroundColor = [UIColor clearColor];
        return headerView;
    }
    return nil;
}

@end 
